package com.novoda.runbuddy.util;

import static positron.harness.IOUtils.basename;
import static positron.harness.IOUtils.cp;
import static positron.harness.IOUtils.ls;
import static positron.harness.IOUtils.mv;

import java.io.File;

import android.content.Context;
import android.util.Log;

/*
 * This class is a modified class taken from Positron.
 * 
 * The same license applies.
 * 
 */
public class DatabaseArchiver {
	private static final String	TAG	= "TestRunner";

	private final Context		mContext;

	public DatabaseArchiver(Context context) {
		this.mContext = context;
	}

	/** Backup all databases in the target context. */
	public void backup() {
		// by DTM
		String dir = databaseDir();
		if (dir != null) {
			for (String database : ls(dir, ".*\\.db")) {
				database = basename(database);
				if (isBackup(database))
					continue;
				backup(database);
			}
		}
	}

	/** Restore all databases that have backups in the target context. */
	public void restore() {
		// by DTM
		String dir = databaseDir();
		if (dir != null) {
			for (String backup : ls(dir, ".*_backup\\.db")) {
				String database = basename(backup).replaceFirst("_backup", "");
				restore(database);
			}
		}
	}

	/**
	 * Back up the given database by copying its defining file out of the way.
	 * 
	 * This blows away any previous backup.
	 * 
	 * @param database
	 *            The database to back up.
	 */
	public void backup(String database) {
		Log.i(TAG, "Backing up " + database);
		cp(locationOf(database), locationOf(backupOf(database)));
	}

	/**
	 * Restore the given database by copying the backup file back in place.
	 * 
	 * @param database
	 *            The database to restore.
	 */
	public void restore(String database) {
		Log.i(TAG, "Restoring " + database);
		mv(locationOf(backupOf(database)), locationOf(database));
	}

	private String locationOf(String database) {
		return databaseDir() + "/" + database;
	}

	private String databaseDir() {
		// by DTM
		// perhaps there's no database dir in this application
		String dir = "/data/data/" + mContext.getPackageName() + "/databases";
		if (!new File(dir).isDirectory()) {
			// there's no database dir
			return null;
		}

		return dir;
	}

	private String backupOf(String database) {
		return database.replaceAll("\\.db$", "_backup.db");
	}

	private boolean isBackup(String database) {
		return database.matches(".*_backup\\.db$");
	}
}
